package com.mc.book.utils.wxpay;

import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.mc.book.utils.wxpay.WxPayProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 微信支付自动配置类
 * @author TangChao
 * @create 2022/08/11
 */
@Slf4j
@Configuration
@AllArgsConstructor
@EnableConfigurationProperties({WxPayProperties.class})
public class WxAutoConfiguration {

    private WxPayProperties payProperties;


    @Bean
    @ConditionalOnMissingBean
    @ConditionalOnClass(WxPayService.class)
    public WxPayService wxService() {
        WxPayConfig payConfig = new WxPayConfig();
        payConfig.setAppId(StringUtils.trimToNull(this.payProperties.getAppId()));
        payConfig.setMchId(StringUtils.trimToNull(this.payProperties.getMchId()));
        payConfig.setMchKey(StringUtils.trimToNull(this.payProperties.getMchKey()));
//        payConfig.setSubAppId(StringUtils.trimToNull(this.payProperties.getSubAppId()));
//        payConfig.setSubMchId(StringUtils.trimToNull(this.payProperties.getSubMchId()));
        payConfig.setKeyPath(StringUtils.trimToNull(this.payProperties.getKeyPath()));
        // v3
//        payConfig.setApiV3Key(StringUtils.trimToNull(this.payProperties.getApiV3Key()));
//        payConfig.setCertSerialNo(StringUtils.trimToNull(this.payProperties.getCertSerialNo()));
//        payConfig.setPrivateCertPath(StringUtils.trimToNull(this.payProperties.getPrivateCertPath()));
//        payConfig.setPrivateKeyPath(StringUtils.trimToNull(this.payProperties.getPrivateKeyPath()));
        payConfig.setNotifyUrl(StringUtils.trimToNull(this.payProperties.getNotifyURL()));
//        payConfig.setTradeType(WxPayConstants.TradeType.MWEB);

        //不使用沙箱环境
        payConfig.setUseSandboxEnv(false);

        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(payConfig);
        log.info("微信PAY init");
        return wxPayService;
    }
}